
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;
using Abp.Runtime.Session;
using JYJ.AiYard.StationManagement.TbDiscountBills;
using JYJ.AiYard.StationManagement.TbDiscountBills.Dtos;
using JYJ.AiYard.StationManagement.TbDiscountBills.DomainService;
using JYJ.AiYard.StationManagement.TbDiscountBills.Authorization;
using JYJ.AiYard.Database;
using JYJ.AiYard.Common;
using JYJ.AiYard.StationManagement.YardCommonHald;
using Microsoft.AspNetCore.Http;
using JYJ.AiYard.StationManagement.YardReport.Authorization;

namespace JYJ.AiYard.StationManagement.TbDiscountBills
{
    /// <summary>
    /// TbDiscountBill应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbDiscountBillAppService : AiYardAppServiceBase, ITbDiscountBillAppService
    {

        #region 构造函数
        private readonly IRepository<TbDiscountBill, long> _entityRepository;

        private readonly ITbDiscountBillManager _entityManager;

        private readonly IAiYardDbTableIssuedCard _aiYardDbTableIssuedCard;

        private readonly IHttpService _httpService;

        protected IHttpContextAccessor _httpContext;
        /// <summary>
        /// 构造函数 
        ///</summary>
        public TbDiscountBillAppService(
            IRepository<TbDiscountBill, long> entityRepository
            , ITbDiscountBillManager entityManager,
            IAiYardDbTableIssuedCard aiYardDbTableIssuedCard
              , IHttpService httpService
             , IHttpContextAccessor httpContextAccessor
        )
        {
            _entityRepository = entityRepository;
            _entityManager = entityManager;
            _aiYardDbTableIssuedCard = aiYardDbTableIssuedCard;
            _httpService = httpService;
            _httpContext = httpContextAccessor;
        }
        #endregion

        #region 查询新增修改删除 
        /// <summary>
        /// 获取TbDiscountBill的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbDiscountBillPermissions.Query)]
        public async Task<PagedResultDto<TbDiscountBillMaster>> GetPaged(GetTbDiscountBillsInput input)
        {
            List<long> StationList = new List<long>();
            BillFilterText filterText = input.FilterText.ToObject<BillFilterText>();
            if (filterText.StationId == null || filterText.StationId <= 0)
            {
                StationList = GetCurrenUserOrganizationAndChildrenUnit();
            }
            else
            {
                StationList.Add((long)filterText.StationId);
            }
            //判断是否是商户，如果是商户则只显示自己的数据，其它则显示
            int SaleID = _aiYardDbTableIssuedCard.IsUserOrganizationUnit(Convert.ToInt64(AbpSession.UserId));
            var query1 = _aiYardDbTableIssuedCard.GetTbDiscountBillMaster(StationList, input.FilterText, SaleID);

            var query = query1.AsQueryable();
            var count = query.Count();


            var entityList = query
            .OrderBy(input.Sorting)
            .PageBy(input)
            .ToList().OrderByDescending(o => o.tCreateTime).ToList();
            return new PagedResultDto<TbDiscountBillMaster>(count, entityList);


        }


        /// <summary>
        /// 通过指定id获取TbDiscountBillListDto信息
        /// </summary>
        [AbpAuthorize(TbDiscountBillPermissions.Query)]
        public async Task<TbDiscountBillListDto> GetById(EntityDto<long> input)
        {
            var entity = await _entityRepository.GetAsync(input.Id);

            return entity.MapTo<TbDiscountBillListDto>();
        }

        /// <summary>
        /// 获取编辑 TbDiscountBill
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbDiscountBillPermissions.Create)]
        public async Task<GetTbDiscountBillForEditOutput> GetForEdit(NullableIdDto<long> input)
        {
            var output = new GetTbDiscountBillForEditOutput();
            TbDiscountBillEditDto editDto;

            if (input.Id.HasValue)
            {
                var entity = await _entityRepository.GetAsync(input.Id.Value);

                editDto = entity.MapTo<TbDiscountBillEditDto>();

            }
            else
            {
                editDto = new TbDiscountBillEditDto();
            }

            output.TbDiscountBill = editDto;
            return output;
        }


        /// <summary>
        /// 添加或者修改TbDiscountBill的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbDiscountBillPermissions.Create)]
        public async Task<Dictionary<string,string>> CreateOrUpdate(CreateOrUpdateTbDiscountBillInput input)
        {
            if (input.TbDiscountBill.Station_ID <= 0)
            {
                throw new UserFriendlyException("请选择确定的场所名称");
            }
            if (input.TbDiscountBill.Id.HasValue)
            {
                //不可以修改 
                return new Dictionary<string, string>();
            }
            else
            {
                return await Create(input.TbDiscountBill);
            }
        }


        /// <summary>
        /// 生成TbDiscountBill
        /// </summary>
        [AbpAuthorize(TbDiscountBillPermissions.Create)]
        protected virtual async Task<Dictionary<string,string>> Create(TbDiscountBillEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            Dictionary<string, string> result = new Dictionary<string, string>();
            try
            {
                var entity = input.MapTo<TbDiscountBill>(); 

                int verresult = 1;
                //验证有无商户
                if (entity.TsaleId < 1)
                {
                    verresult = 0;
                    result.Add("retype", "-1");
                    result.Add("revalue", "未选择商户");
                    return result;
                }
                
                
                //验证券头等于组织ID(16进制)+商户ID(16进制)共4位
                entity.TbillNo = YardCommon.Hex10To16(Convert.ToInt32(input.Station_ID)).PadLeft(2,'0') +
                                 YardCommon.Hex10To16(Convert.ToInt32(entity.TsaleId)).PadLeft(2,'0');
                entity.TcreateOpId = Convert.ToInt32(AbpSession.UserId);
                
                //验证
                if (entity.DiscountCount < 1)
                {
                    verresult = 0;
                    result.Add("retype", "-1");
                    result.Add("revalue", "优惠券数量不正确");
                    return result;
                }
                //不能大于1000张
                if (entity.DiscountCount > 1000)
                {
                    verresult = 0;
                    result.Add("retype", "-1");
                    result.Add("revalue", "优惠券数据不能大于1000张");
                    return result;
                }
                //验证有效期是否正确
                if (entity.Texdt < entity.Tbedt)
                {
                    verresult = 0;
                    result.Add("retype", "-1");
                    result.Add("revalue", "有效结束时间小于有效开始时间");
                    return result;
                }

                entity.TenantId = Convert.ToInt32(AbpSession.TenantId);

                if (verresult == 1)
                { 
                    result = _aiYardDbTableIssuedCard.AddDiscountBills(entity);
                }
            }
            catch(Exception ex)
            {
                result.Add("retype", "-1");
                result.Add("revalue", "发生错误");
            }
             

            return result;
        }
        #endregion

        #region 删除发行的券--未支付部分
        [AbpAuthorize(TbDiscountBillPermissions.Create)]
        public async Task<bool> DeleteDiscountBill(long Id)
        {
            try
            {
                return _aiYardDbTableIssuedCard.DeleteDiscountBill(Id, AbpSession.UserId,false);
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        #region 删除发行的券--包括所有
        [AbpAuthorize(TbDiscountBillPermissions.BatchDelete)]
        public async Task<bool> BatchDeleteDiscountBill(List<long> input)
        {
            try
            {
                foreach (long pk in input)
                {
                    _aiYardDbTableIssuedCard.DeleteDiscountBill(pk, AbpSession.UserId,true);
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        #region 删除发行的券--明细
        [AbpAuthorize(TbrInYardPermissions.TbrDiscountBatchDelete)]
        public async Task<bool> BatchUpdateDiscountBillMX(List<long> Id)
        {
            try
            {
                return _aiYardDbTableIssuedCard.DeleteDiscountBill(Id, AbpSession.UserId); 
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        #region 二维码支付
        public List<NATivePayResponse> GetPayUrl(long Id)
        {
            List<NATivePayResponse> nATivePayResponse = new List<NATivePayResponse>();
            try
            {
                TbDiscountBillMaster input = new TbDiscountBillMaster();
                input = _aiYardDbTableIssuedCard.GetTbDiscountBillMasterById(Id);
                //验证当前车辆是否开通无感支付
                NATivePayRequest request = new NATivePayRequest();
                request.Station_Id =  Convert.ToInt64(input.Station_ID);
                request.Station_No =  input.Station_No;
                request.Station_Name = input.Station_Name;
                request.Client_Id = 1;
                request.Client_No = System.Net.Dns.GetHostName().Trim();
                request.Client_Name = System.Net.Dns.GetHostName().Trim();
                request.nATive = new NATivePayModels();
                request.nATive.Amount = Convert.ToInt32(input.SumTamount * 100);
                request.nATive.goods_tag = "购买停车券";
                request.nATive.paysource = 4;
                request.nATive.Pay_subject = input.Sale_Name + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "支付停车券";
                request.nATive.RecordId = Convert.ToInt32(input.Id);
                request.nATive.merchant_param = "";
                request.nATive.tiveType = NATiveType.服务端决定;
                string nonce = Guid.NewGuid().ToString().Replace("{","").Replace("}","").Replace("-","").Left(8);
                request.Nonce = nonce;
                //MD5.MD5Encrypt(Text.ToUpper() + nonce.ToLower() + Key.ToLower()).ToLower()
                request.Sign = MD5.MD5Encrypt(request.nATive.ToJson().ToUpper() + nonce.ToLower() + input.Station_MD5Key.ToLower()).ToLower();
                string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.","t.");
#if DEBUG
                host = "pay.aiyard.cn";
#endif
                string response = _httpService.Post(request.ToJson(), (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/Api/v1.0/BarCodePay/codeNATivePay", 120);
            
                ApiReturn apireturn = Json.ToObject<ApiReturn>(response);  


                if (apireturn.result == 200)
                {
                    ApiObject check = Json.ToObject<ApiObject>(response);
                    List<NATivePayResponse> obj = Json.ToList<NATivePayResponse>(check.msg.ToJson());
                    //序列号化之后小数位数会丢失导致验签不成功
                    string sign = MD5.MD5Encrypt(("[" + response.Split('[')[1].Split(']')[0] + "]").ToUpper() + apireturn.nonce.ToLower() + input.Station_MD5Key.ToLower()).ToLower();
                    if (sign != apireturn.sign)
                    {

                    }
                    else
                    {
                        for (int i = 0; i < obj.Count; i++)
                        {
                            if (obj[i].result == "Success")
                            {
                                nATivePayResponse.Add(obj[i]);
                            }
                        }
                    }

                }
                else
                {

                }

            }
            catch (Exception ex)
            { 

            }
            return nATivePayResponse;
        }
        #endregion

        ///// <summary>
        ///// 编辑TbDiscountBill
        ///// </summary>
        //[AbpAuthorize(TbDiscountBillPermissions.Edit)]
        //protected virtual async Task Update(TbDiscountBillEditDto input)
        //{
        //	//TODO:更新前的逻辑判断，是否允许更新

        //	var entity = await _entityRepository.GetAsync(input.Id.Value);
        //	input.MapTo(entity);

        //	// ObjectMapper.Map(input, entity);
        //    await _entityRepository.UpdateAsync(entity);
        //}



        ///// <summary>
        ///// 删除TbDiscountBill信息的方法
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[AbpAuthorize(TbDiscountBillPermissions.Delete)]
        //public async Task Delete(EntityDto<long> input)
        //{
        //	//TODO:删除前的逻辑判断，是否允许删除
        //	await _entityRepository.DeleteAsync(input.Id);
        //}



        ///// <summary>
        ///// 批量删除TbDiscountBill的方法
        ///// </summary>s
        //[AbpAuthorize(TbDiscountBillPermissions.BatchDelete)]
        //public async Task BatchDelete(List<long> input)
        //{
        //	// TODO:批量删除前的逻辑判断，是否允许删除
        //	await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
        //}




    }
}


